#include "Game.h"
#include <iostream>
#include <vector>
#include <mmsystem.h>
#include "imageManager.h"
#include "Animation.h"
#include "AssetsManager.h"
#include "time.h"
#include <sstream>
#include <string>
#pragma comment(lib,"winmm.lib")
//Note note;

AssetsManager aManager;

ExMessage Game::msg;


int Game::run()
{

	while (m_isRunning)
	{
		handLeMsg();
		update();
		render();
		Sleep(5);
	}

	return 0;
}


bool Game::init(int w, int h)
{
	srand(time(NULL));

	initgraph(w, h, EX_SHOWCONSOLE);

	auto im = imageManager::getInstaance();


	im->cacheImage("background", "Resource/images/bg.jpg");

	im->cacheImage("dLine", "Resource/images/dLine.jpg", 1280, 15);

	im->cacheImage("tapA", "Resource/images/taA.png", 150, 20);

	im->cacheImage("tapB", "Resource/images/taB.png", 150, 20);

	char buf[128];
	//循环 添加图片
	for (int i = 0; i < 32; i++)
	{
		//用C 批量处理 路径
		sprintf_s(buf, "Resource/images/effects/effect_ %02d.png", i);
		im->cacheImage(std::to_string(i),buf , 200, 200);
	}


	
	//打开音乐
	mciSendString("open Resource/images/bgm.mp3", NULL, 0, NULL);
	// 播放音乐
	mciSendString("play Resource/images/bgm.mp3", NULL, 0, NULL);


	m_startIime = clock();

	m_isRunning = true;

	return m_isRunning;
}

void Game::clean()
{
}

void Game::update()
{

	m_duration = (clock() - m_startIime) / 1000; //获取秒树
	aManager.refersh();
	aManager.update();
	//std::cout << __FUNCTION__ << std::endl;
	//std::cout << "" << std::endl;
	// 四秒钟之后才添加
	static int t1 = 0;

	if (m_duration >= 2) {

		if (clock() - t1 > 1000) {
			aManager.addNote(rand() % (getwidth() - 200), -40);
			t1 = clock();
		}
	}
	//判断当前下落块是否在判断线上面

	 //判断消息用户是否按下空格键
	if (msg.message == WM_KEYDOWN && msg.vkcode == VK_SPACE) {
		//获取当前方块的对象
		auto& notes = aManager.notes();
		for (auto& n : notes) {
			//循环判断当前的方块是否在判定线上面
			if (n->getY() >= 500 - 20 && n->getY() <= 500 + 30) {
				//释放当前方块 
				//判断 当前方块类型 如果是 tapA 加两分  如果是tapB 加 4分
				if (n->getType()==0) {
					m_F += 2;
				}
				else
				{
					m_F += 4;
				}
	
				//移除方块
				n->destroy();

	

				//播放销毁音乐  异步
				PlaySound("Resource/sound/SFX_Tap.wav", NULL, SND_FILENAME | SND_ASYNC);
				// 播放销毁动画
				aManager.addAnimation(n->getX(), n->getY()-100, 30);
			}
		}
	}



	//std::cout <<  << std::endl;
}

void Game::render()
{
	/***************************************/
	BeginBatchDraw();   //

	cleardevice(); //

	//
	putimage(0, 0, imageManager::getInstaance()->getImage("background"));

	//
	imageManager::drawImg(0, 500, imageManager::getInstaance()->getImage("dLine"));

	



	std::stringstream ss;
	ss << m_F;
	std::string str = ss.str();



	settextstyle(40, 0, _T("宋体"));

	outtextxy(20, 60, _T(str.c_str()));


	outtextxy(20, 20, _T("a"));






	aManager.render();
	EndBatchDraw(); // 


	/***************************************/
}
//
void Game::handLeMsg()
{
	if (peekmessage(&msg)) {

		if (msg.message == WM_KEYDOWN) {
			if (msg.vkcode == VK_ESCAPE) {
				outGame();
			}

		}
	}

}
